﻿using CCWin;
using DBToExcel.Code;
using DBToExcel.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DBToExcel
{
    public partial class EditDBConn : Skin_Metro
    {
        private MDBConn _model = null;

        public EditDBConn()
        {
            InitializeComponent();
            LoadDrivers();
            _model = _model == null ? new MDBConn():_model;
        }

        public EditDBConn(string id):this() {
            List<MDBConn> list= ExcelBuilderService.QueryAllMDBConns();
            if (list!=null&&list.Count>0)
            {
                _model = list.FirstOrDefault(x => x.Id.Equals(id));
            }

            if (_model == null) {
                if (MessageBoxEx.Show("不存在该连接信息", "异常", MessageBoxButtons.OK)==DialogResult.OK)
                {
                    this.Close();
                }

                return;
            }

            SetModelData();
        }

        private void skinLabel4_Click(object sender, EventArgs e)
        {

        }

        private void LoadDrivers() {
            List<ComboBoxItem> list= FileConfig.GetDrivers();
            if (list == null || list.Count == 0) {
                return;
            }

            list.ForEach(x => {
                this.drivertype.Items.Add(x);
            });
        }

        private void SetModelData() {
            this.connname.Text = _model.Name;
            this.drivertype.SelectedItem = this.drivertype.Items.Cast<ComboBoxItem>().FirstOrDefault(x => x.Value.Equals(_model.FileName));
            this.drivertype.SelectedValue = _model.FileName;
            this.classname.Text = _model.ClassName;
            this.connstr.Text = _model.ConnStr;
        }

        private void drivertype_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBoxItem item= this.drivertype.SelectedItem as ComboBoxItem;
            if (item==null)
            {
                return;
            }
            string path = item.Value.ToString();
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            Type connType = GetConnClassType(path);
            if (connType != null) {
                this.classname.Text = connType.FullName;
            }
        }

        private Type GetConnClassType(string path) {
            Assembly assembly= Assembly.LoadFrom(path);
            Type[] types = assembly.GetTypes();
            if (types == null || types.Length == 0) {
                return null;
            }
            Type type = types.FirstOrDefault(x => x.IsClass && x.BaseType== typeof(DbConnection));
            return type;
        }

        private void testconnbtn_Click(object sender, EventArgs e)
        {
            Loading.ShowLayer(this, () =>
            {
                try
                {
                    TestConn();
                }
                catch (Exception ex)
                {
                    MessageBoxEx.Show(ex.Message);
                }
            });

        }

        /// <summary>
        /// 测试连接
        /// </summary>
        /// <returns></returns>
        private bool TestConn() {
            MDBConn mDBConn = new MDBConn();
            mDBConn.Name = this.connname.Text;
            ComboBoxItem item = this.drivertype.SelectedItem as ComboBoxItem;
            if (item != null)
            {
                mDBConn.FileName = item.Value.ToString();
            }
            mDBConn.ClassName = this.classname.Text;
            mDBConn.ConnStr = this.connstr.Text;
            string result = DBConnUtils.TestConn(mDBConn);
            bool success = string.IsNullOrEmpty(result);
            if (success)
            {
                result = "连接成功！";
            }

            MessageBoxEx.Show(result);

            return success;
        }


        private void savebtn_Click(object sender, EventArgs e)
        {
            _model.Name = this.connname.Text;
            if (string.IsNullOrEmpty(_model.Name))
            {
                MessageBoxEx.Show("连接名称不能为空");
                return;
            }

            ComboBoxItem item = this.drivertype.SelectedItem as ComboBoxItem;
            if (item == null)
            {
                MessageBoxEx.Show("驱动类型不能为空");
                return;
            }

            _model.FileName = item.Value.ToString();


            _model.ClassName = this.classname.Text;
            if (string.IsNullOrEmpty(_model.ClassName))
            {
                MessageBoxEx.Show("连接类名不能为空");
                return;
            }

            _model.ConnStr = this.connstr.Text;
            if (string.IsNullOrEmpty(_model.ConnStr))
            {
                MessageBoxEx.Show("连接字符串不能为空");
                return;
            }

            ExcelBuilderService.SaveDBConn(_model);
            MessageBoxEx.Show("保存成功！");
        }
    }
}
